import json
import os
import time
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Callable

from app.core.config import settings
from app.core.logging import logger
from app.models.messages import MessageDirection, MessageStatus, MessageType


class WeChatHook:
    """微信消息Hook服务，用于实时捕获微信消息"""
    
    def __init__(self):
        """初始化微信Hook服务"""
        logger.info("Initializing WeChat Hook Service")
        self.data_dir = settings.WECHAT_DATA_DIR
        self.handlers = []  # 消息处理器列表
        self.running = False
        
        # 确保数据目录存在
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)
    
    def register_handler(self, handler: Callable[[Dict[str, Any]], None]) -> None:
        """
        注册消息处理器
        
        Args:
            handler: 消息处理函数，接收消息字典作为参数
        """
        self.handlers.append(handler)
        logger.info(f"Registered message handler: {handler.__name__}")
    
    def start(self) -> None:
        """
        启动Hook服务
        """
        if self.running:
            logger.warning("WeChat Hook Service is already running")
            return
        
        logger.info("Starting WeChat Hook Service")
        self.running = True
        
        # TODO: 实现真正的WeChat Hook逻辑
        # 这里暂时使用模拟实现
        self._start_mock_hook()
    
    def stop(self) -> None:
        """
        停止Hook服务
        """
        if not self.running:
            logger.warning("WeChat Hook Service is not running")
            return
        
        logger.info("Stopping WeChat Hook Service")
        self.running = False
    
    def _start_mock_hook(self) -> None:
        """
        启动模拟Hook服务
        """
        logger.info("Starting mock WeChat Hook Service")
        
        # 创建一个模拟消息捕获线程
        import threading
        self.mock_thread = threading.Thread(target=self._mock_message_loop)
        self.mock_thread.daemon = True
        self.mock_thread.start()
    
    def _mock_message_loop(self) -> None:
        """
        模拟消息捕获循环
        """
        logger.info("Mock message loop started")
        
        # 模拟会话和联系人
        mock_sessions = [
            {"name": "文件传输助手", "type": "individual"},
            {"name": "测试用户1", "type": "individual"},
            {"name": "测试用户2", "type": "individual"},
            {"name": "测试群1", "type": "group"}
        ]
        
        # 模拟消息模板
        mock_message_templates = [
            {"sender": "测试用户1", "content": "你好，最近怎么样？", "direction": MessageDirection.INCOMING},
            {"sender": "我", "content": "还不错，在开发一个新项目", "direction": MessageDirection.OUTGOING},
            {"sender": "测试用户1", "content": "听起来很有趣，是什么项目？", "direction": MessageDirection.INCOMING},
            {"sender": "我", "content": "一个微信聊天助手，可以分析聊天记录", "direction": MessageDirection.OUTGOING},
            {"sender": "测试用户1", "content": "哇，那我们现在的对话也会被分析吗？", "direction": MessageDirection.INCOMING},
            {"sender": "我", "content": "是的，如果你同意的话", "direction": MessageDirection.OUTGOING},
            {"sender": "测试用户2", "content": "听说你在开发一个新项目？", "direction": MessageDirection.INCOMING},
            {"sender": "我", "content": "是的，一个聊天分析助手", "direction": MessageDirection.OUTGOING},
            {"sender": "测试用户2", "content": "你为什么要做这个呢？有什么特别的原因吗？", "direction": MessageDirection.INCOMING},
            {"sender": "我", "content": "主要是想帮助人们改善沟通方式", "direction": MessageDirection.OUTGOING}
        ]
        
        count = 0
        while self.running:
            try:
                # 每10秒模拟一条新消息
                time.sleep(10)
                
                # 选择一个随机会话
                import random
                session = random.choice(mock_sessions)
                
                # 选择一个随机消息模板
                message_template = random.choice(mock_message_templates)
                
                # 创建消息对象
                message = {
                    "session_name": session["name"],
                    "session_type": session["type"],
                    "sender": message_template["sender"],
                    "content": message_template["content"] + f" (#{count})",
                    "sent_at": datetime.now(),
                    "direction": message_template["direction"],
                    "msg_type": MessageType.TEXT,
                    "status": MessageStatus.SENT
                }
                
                # 保存到本地
                self._save_message(message)
                
                # 调用所有处理器
                for handler in self.handlers:
                    try:
                        handler(message)
                    except Exception as e:
                        logger.error(f"Handler {handler.__name__} error: {str(e)}")
                
                count += 1
            except Exception as e:
                logger.error(f"Mock message loop error: {str(e)}")
    
    def _save_message(self, message: Dict[str, Any]) -> None:
        """
        保存消息到本地
        
        Args:
            message: 消息对象
        """
        try:
            # 创建会话目录
            session_name = message["session_name"]
            session_dir = os.path.join(self.data_dir, self._sanitize_filename(session_name))
            if not os.path.exists(session_dir):
                os.makedirs(session_dir)
            
            # 缓存文件路径
            cache_file = os.path.join(session_dir, "messages.json")
            
            # 读取现有缓存
            existing_messages = []
            if os.path.exists(cache_file):
                try:
                    with open(cache_file, 'r', encoding='utf-8') as f:
                        existing_messages = json.load(f)
                except Exception as e:
                    logger.error(f"读取缓存文件失败: {str(e)}")
            
            # 转换日期时间为字符串
            msg_copy = message.copy()
            if isinstance(msg_copy["sent_at"], datetime):
                msg_copy["sent_at"] = msg_copy["sent_at"].strftime("%Y-%m-%d %H:%M:%S")
            
            # 添加新消息
            existing_messages.append(msg_copy)
            
            # 保存到文件
            with open(cache_file, 'w', encoding='utf-8') as f:
                json.dump(existing_messages, f, ensure_ascii=False, indent=2)
            
            logger.debug(f"已保存新消息到缓存: {cache_file}")
        except Exception as e:
            logger.error(f"保存消息到缓存失败: {str(e)}")
    
    def _sanitize_filename(self, filename: str) -> str:
        """
        清理文件名，移除不允许的字符
        
        Args:
            filename: 原始文件名
            
        Returns:
            str: 清理后的文件名
        """
        # 替换不允许的字符
        invalid_chars = '<>:"/\\|?*'
        for char in invalid_chars:
            filename = filename.replace(char, '_')
        
        return filename


# 创建单例实例
wechat_hook = WeChatHook()